package team.zero.lemon.module.workflow.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import team.zero.lemon.common.authz.annotation.AuthPassport;
import team.zero.lemon.common.authz.annotation.AuthPermission;
import team.zero.lemon.common.exception.CustomException;
import team.zero.lemon.common.persistence.Page;
import team.zero.lemon.module.workflow.entity.Form;
import team.zero.lemon.module.workflow.entity.FormData;
import team.zero.lemon.module.workflow.entity.FormDefinition;
import team.zero.lemon.module.workflow.entity.Parameter.FormParameter;
import team.zero.lemon.module.workflow.entity.Parameter.Submit;
import team.zero.lemon.module.workflow.service.FormDataService;
import team.zero.lemon.module.workflow.service.FormDefinitionService;
import team.zero.lemon.module.workflow.service.FormService;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by Bo on 2016/10/24.
 */


@Controller
@ResponseBody
@AuthPassport
@RequestMapping(value = "/workflow/form", method = {RequestMethod.POST, RequestMethod.GET})
public class FormController {

    @Autowired
    private FormService formService;

    @Autowired
    private FormDataService formDataService;

    @Autowired
    private FormDefinitionService definitionService;


    @AuthPassport
    @RequestMapping("/query/page")
    public Page<Form> submit(@RequestBody Form form) {
        return formService.findPage(form);

    }

    @AuthPassport
    @RequestMapping("/save")
    public int saveform(@RequestBody Form form) {
        return formService.save(form);
    }

    @AuthPassport
    @RequestMapping("/definition/save")
    public int saveDefinition(HttpServletRequest request, @RequestBody FormParameter formParameter) {
        if (formParameter.getListForm().size() == 0)
            return 1;
        String path = request.getRealPath("/views/workflow/formfiles");

        formService.SaveForm(formParameter);



        OutputStreamWriter out = null;
        try {
            File file = new File(path + "/" + formParameter.getListForm().get(0).getTemplateId() + ".html");
            if (file.exists()) {
                File file1 = new File(path + "/" + file.getName() + System.currentTimeMillis() + ".html");
                file.renameTo(file1);
            }
            out = new OutputStreamWriter(new FileOutputStream(path + "/" + formParameter.getListForm().get(0).getTemplateId() + ".html"), "UTF-8");
            out.write(formParameter.getHtml());
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                out.flush();
                out.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        return 1;

    }

    @AuthPassport
    @RequestMapping("/definition/find/formId")
    public List<FormDefinition> findDefinitionbyForm(@RequestBody Form form) {
        return definitionService.findByFormId(form.getId());
    }


    @AuthPassport
    @RequestMapping("/find/templateId")
    public List<Form> findFormbyTemplate(@RequestBody Form form) {
        return formService.findFormbyTemplate(form.getId());

    }

    @AuthPassport
    @RequestMapping("/data/save")
    public boolean saveDatas(@RequestBody List<FormData> formdatas) {
        try {
            if (formdatas.size() > 0) {
                List<String> formNames = new ArrayList<>();
                formdatas.forEach(a -> {
                    if (!formNames.contains(a.getFormName()))
                        formNames.add(a.getFormName());
                });
                formNames.forEach(a->{
                    formDataService.deleteByInstanceId(formdatas.get(0).getInstanceId(),a);
                });


                formDataService.save(formdatas);
            }
            return true;
        } catch (Exception ex) {
            throw new CustomException(ex);
        }
    }

    @AuthPassport
    @RequestMapping("/data/find")
    public List<FormData> findDatas(@RequestBody FormData formdata) {
        try {
            return formDataService.findbyInstanceId(formdata.getInstanceId());
        } catch (Exception ex) {
            throw new CustomException(ex);
        }
    }
}
